package com.yc154.vote.controller;

import com.yc.starter.login.LoginProperties;
import com.yc154.vote.entity.Result;
import com.yc154.vote.entity.User;
import com.yc154.vote.service.BizException;
import com.yc154.vote.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiaoYan
 * @since 2025-09-20
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private LoginProperties loginProperties;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Result login(String uname, String pwd, HttpSession session) {
        if (uname == null || uname.isEmpty()) {
            throw new BizException("用户名不能为空", null);
        }
        if (pwd == null || pwd.isEmpty()) {
            throw new BizException("密码不能为空", null);
        }

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUname, uname)
           .eq(User::getPwd, pwd);
        User user = userService.getOne(lqw);

        if (user != null) {
            // 登录成功，将用户信息存入session
            String sessionKey = loginProperties.getSessionKey();
            session.setAttribute(sessionKey, user);
            return Result.ok("登录成功", user);
        } else {
            throw new BizException("用户名或密码错误", null);
        }
    }



    @RequestMapping("logout")
    public Result logout(HttpSession session) {
        String sessionKey = loginProperties.getSessionKey();
        session.removeAttribute(sessionKey);
        return Result.ok("退出登录成功", null);
    }

    @RequestMapping("getCurrentUser")
    public Result getCurrentUser(HttpSession session) {
        String sessionKey = loginProperties.getSessionKey();
        User user = (User) session.getAttribute(sessionKey);
        if (user != null) {
            return Result.ok("获取用户信息成功", user);
        } else {
            throw new BizException("用户未登录", null);
        }
    }
}
